import React from "react";
import BaseFormItem from "../Base/BaseFormItem";
import {forEach, forIn, indexOf, isArray, isEmpty, isFunction, keys, map, omit} from "lodash-es";
import {Checkbox, Select} from "antd";
import BaseField from "../Base/BaseField";
import ComboCache from "../ComboBox/ComboCache";
import {comboApi} from "../Config/GlobalApi";
import {getRandomKey} from "jh-utils";

const {Option} = Select;

/**
 * 嵌入式复选级控件
 * ComponentType.EMBED_SELECTOR
 */
export class EmbedSelectorBase extends BaseField {

    static propTypes = {
        ...BaseField.propTypes
    };


    get cacheKey() {
        return this.getPropsByName('selector');
    }

    /**
     *
     * @type {{}}
     */
    set listCache(value) {
        ComboCache.addCache(this.cacheKey, value);
    }

    get listCache() {
        return ComboCache.getCache(this.cacheKey);
    }

    set loadingList(value) {
        ComboCache.loading[this.cacheKey] = value;
    }

    get loadingList() {
        return ComboCache.loading[this.cacheKey];
    }

    abortCtrl = {};

    randomKey = getRandomKey();

    moreCommonProps() {
        return [
            ...super.moreCommonProps(),
            'defaultOpen', 'selector', 'belong', 'fetchList', 'custEmbed'
        ]
    }

    initState(props) {
        return {
            ...super.initState(props),
            loading: false,
            list: props.compData || []
        };
    }

    componentDidMount() {
        super.componentDidMount && super.componentDidMount();

        this.fetchData();
    }

    componentWillUnmount() {
        super.componentWillUnmount();

        const cacheKey = this.cacheKey;
        if (cacheKey) {
            ComboCache.removeLoadingIns(cacheKey, this.randomKey);
        }
    }


    fetchData() {
        this.runBeforeCbs();

        // 先读缓存
        const listCache = this.listCache;

        if (!isEmpty(listCache)) {

            this.setState({
                list: listCache
            }, () => {
                this.runPropsFunc('onDataLoad')(listCache);
            });

        } else {

            const $this = this;
            const {appins, selector, fetchList, onDataLoad} = this.getProps();

            const fetchFunc = isFunction(fetchList) ? fetchList : ( // 取 props.fetchList
                appins && appins.fetchCombo ? appins.fetchCombo.bind(appins) : ( // 取 appins.fetchCombo
                    this.fetchFunc.bind(this) // 取 this.fetchFunc
                )
            );

            if (selector && isFunction(fetchFunc)) {
                let cacheKey = this.cacheKey;

                if (this.loadingList) {
                    ComboCache.addLoadingIns(cacheKey, this.randomKey, this);
                    this.setState({loading: true});
                    return false;
                }

                this.loadingList = true;
                $this.setState({loading: true});

                const fetchReturn = fetchFunc({
                    code: selector
                });

                if (fetchReturn instanceof Promise) {
                    fetchReturn.then((rsp) => {
                        let newList = [];

                        if (rsp && rsp.status === 200) {
                            const rspData = rsp.data;
                            newList = isArray(rspData) ? rspData : (
                                isArray(rspData.options) ? rspData.options : []
                            )
                        }
                        this.listCache = newList;
                        $this.setState({
                            list: newList,
                            loading: false
                        }, () => {
                            isFunction(onDataLoad) && onDataLoad(newList);
                        });

                        this.loadingList = false;
                        ComboCache.updateComboInstances(cacheKey);
                    });
                } else {
                    $this.setState({loading: false});
                    this.loadingList = false;
                    ComboCache.updateComboInstances(cacheKey);
                }
            }
        }

    }

    fetchFunc(ajaxData, options = {}) {
        // console.log('fetchFunc')
        return this.reqGet(comboApi.api, ajaxData, options);
    }

    hdlValueChange(value) {
        let newVal = {};

        forEach(this.valueObj, (v, k) => {
            newVal[k] = indexOf(value, k) > -1;
        });

        super.hdlValueChange(newVal);
    }

    mainRender(context) {
        const {readonly} = this.getProps();
        const {value, list} = this.state;
        const cProps = omit(this.props, this.commonProps);
        cProps.onChange = this.hdlValueChange.bind(this);
        const options = [];
        const valueArr = [];
        this.valueObj = {};

        forEach(list, (v, k) => {
            if (v) {
                this.valueObj[v.code] = false;
                options.push({
                    label: v.name,
                    value: v.code,
                    // disabled: false
                });
            }
        });

        forIn(value, (v, k) => {
            if (v) {
                valueArr.push(k);
                this.valueObj[k] = v;
            }
        });

        return (
            <Checkbox.Group
                {...cProps}
                disabled={readonly}
                options={options}
                value={valueArr}
                onClick={(e) => {
                    e.stopPropagation();
                }}
            />
        );


        // return (
        //     <Select
        //         mode="multiple"
        //         {...cProps}
        //         value={valueArr}
        //     >
        //         {
        //             map(options, (opt) => (
        //                 <Option key={opt.value} value={opt.value}>
        //                     {opt.value}
        //                 </Option>
        //             ))
        //         }
        //     </Select>
        // );
    }
}

export default class EmbedSelector extends BaseFormItem {

    static defaultProps = {
        className: 'check-group'
    };

    Comp = EmbedSelectorBase;
}